<?php
/**
 * Created by PhpStorm.
 * User: yuliang
 * Date: 2017/6/1
 * Time: 下午3:56
 */

namespace app\webapi\controller;


use app\common\controller\Api;
use think\Db;
use think\Request;
use PHPExcel_IOFactory;

class Account extends Api
{
    /**
     * 账号列表
     * @return \think\response\Json
     */
    public function accountList(){
        $token = input('post.token');
        $uid = input('post.uid');
        $page = input('post.page')?input('post.page'):1;
        $pageSize = 6;
        $validate = $this->validate(['uid'=>$uid,'token'=>$token],['uid'=> 'require|number','token'=>'require']);
        if($validate !== true){
            return api_error('1000',$validate);
        }

        $checkToken = $this->checkAuthToken($token);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        $model = Db::name('account');
        $map['status'] = 1;
        $map['uid'] = input('post.uid');

        $logo = Db::name('platform')->field('id,logo')->select();
        $logos = array_column($logo,'logo','id');


        $account = $model->field('result,password,create_time,update_time',true)->where($map)->page($page,$pageSize)->order('update_time desc')->select();
        $count = $model->where($map)->count();

        $result['page'] = ceil($count/$pageSize);
        if(empty($account)){
            $result['data'] = array();
            return api_return('操作成功！',array());
        }else{
            foreach ($account as $key=>$value){
                $account[$key]['logo'] = $logos[$value['platform']];
                $account[$key]['sort_name'] = get_sort_name($value['platform'],$value['sort']);
            }
            $result['data'] = $account;
        }
        return api_return('操作成功！',$result);
    }

    // 账号详情
    public function accountDetail(){
        $token = input('post.token');
        $uid = input('post.uid');
        $account_id = input('account_id');
        $validate = $this->validate(['account_id'=>$account_id],['account_id'=>'require|number']);
        if($validate !== true){
            return api_error('1000',$validate);
        }

        // 进行用户校验
        $checkToken = $this->checkAuthToken($token);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }

        $account = Db::name('account')->where('id',$account_id)->find();
        if(!$account){
            return api_error('3001','对不起，该账号不存在！');
        }else{
            $account['result'] = json_decode($account['result'],true);
            return api_return('操作成功',$account);
        }

    }

    // 删除操作
    public function delAccount(){
        $data['id'] = trim(input('post.id'));
        $data['uid'] = input('post.uid');
        $data['token'] = input('post.token');
        $rule = [
            'id' => 'require|number',
            'uid' => 'require|number',
            'token' => 'require',
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($data['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        $map['uid'] = $data['uid'];
        $map['id'] = $data['id'];
        $result = model('Account')->isUpdate(true)->save(['status'=> '-1'],$map);
        if($result){
            return api_return('删除成功！',array());
        }else{
            return api_error('3002','删除失败！');
        }
    }

    // 用户添加账号分组
    public function addGroup(){
        $data['title'] = input('post.title');
        $data['accounts'] = trim(input('post.accounts'));
        $data['uid'] = input('post.uid');
        $data['token'] = input('post.token');
        $rule = [
//            'accounts' => 'require',
            'uid' => 'require|number',
            'token' => 'require',
            'title' => 'require'
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($data['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        $data['create_time'] = $data['update_time'] = date('Y-m-d H:i:s',time());
        unset($data['token']);
        $result = Db::name('account_group')->insertGetId($data);
        if($result){
            return api_return('添加分组成功！',array());
        }else{
            return api_error('3003','添加分组失败！');
        }
    }

    // 用户编辑账号分组
    public function editGroup(){
        $data['id'] = input('post.id');
        $data['title'] = input('post.title');
        $data['accounts'] = trim(input('post.accounts'));
        $data['uid'] = input('post.uid');
        $data['token'] = input('post.token');
        $rule = [
            'id' => 'require|number',
//            'accounts' => 'require',
            'uid' => 'require|number',
            'token' => 'require',
            'title' => 'require'
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($data['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        $data['update_time'] = date('Y-m-d H:i:s',time());
        unset($data['token']);
        $map['id'] = $data['id'];
        $map['uid'] = $data['uid'];
        $result = Db::name('account_group')->where($map)->update($data);
        if($result){
            return api_return('修改分组成功！',array());
        }else{
            return api_error('3004','修改分组失败！');
        }
    }

    // 用户删除账号分组
    public function delGroup(){
        $data['id'] = input('post.id');
        $data['uid'] = input('post.uid');
        $data['token'] = input('post.token');
        $rule = [
            'id' => 'require|number',
            'uid' => 'require|number',
            'token' => 'require',
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($data['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        unset($data['token']);
        $result = Db::name('account_group')->where($data)->delete();
        if($result){
            return api_return('删除分组成功！',array());
        }else{
            return api_error('3005','删除分组失败！');
        }
    }

    // 用户分组列表
    public function groupList(){
        $token = input('post.token');
        $uid = input('post.uid');
        $page = input('post.page')?input('post.page'):1;
        $pageSize = 6;
        $validate = $this->validate(['uid'=>$uid,'token'=>$token],['uid'=> 'require|number','token'=>'require']);
        if($validate !== true){
            return api_error('1000',$validate);
        }

        $checkToken = $this->checkAuthToken($token);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        $model = model('Group');
        $map['uid'] = input('post.uid');

        $account = $model->field('create_time,update_time',true)->where($map)->page($page,$pageSize)->order('create_time desc')->select();
        $count = $model->where($map)->count();

        $result['page'] = ceil($count/$pageSize);
        if(empty($account)){
            $result['data'] = array();
            return api_return('操作成功！',$result);
        }else{
            foreach ($account as $key=>$value){
                $account[$key]['child'] = $model->child($value['accounts']);
            }
            $result['data'] = $account;
        }
        return api_return('操作成功！',$result);
    }

    // 平台列表
    public function platformList(){
        $data['uid'] = $uid = input('post.uid');
        $data['token'] = input('post.token');
        $rule = [
            'uid' => 'require|number',
            'token' => 'require',
        ];

        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($data['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        $config = config('platform');
        $data = Db::name('platform')->where('status in(1,0)')->order('list_order desc,id asc')->select();
//        $data = Db::name('platform')->order('list_order desc,id asc')->select();
        foreach ($data as $key=>$value){
            switch ($value['id']){
                case 1 :
                    $data[$key]['url'] = 'https://open.snssdk.com/auth/authorize/?response_type=code&auth_only=1'.'&client_key='.$config['sns_key'].'&redirect_uri=http://api.chuanchuan.tv/index.php?s=webapi/auth/sns&display=0&state='.$uid;
                break;
                case 3:
                    $data[$key]['url'] = 'https://openapi.iqiyi.com/api/oauth2/authorize?client_id='.$config['iqiyi_key'].'&response_type=code&redirect_uri=http://api.chuanchuan.tv/index.php?s=webapi/auth/iqiyi&state='.$uid;
                break;
                case 4:
                    $data[$key]['url'] = 'https://auth.om.qq.com/omoauth2/authorize?response_type=code&client_id='.$config['om_key'].'&redirect_uri=http://api.chuanchuan.tv/webapi/auth/om&state='.$uid;
                    break;
                default:
                    $data[$key]['url'] = '';
            }
        }
        return api_return('操作成功!',$data);
    }

    // 添加账号
    public function addAccount(){
        set_time_limit(0);
        $data['account'] = $account = input('post.account');
        $data['platform'] = $platform = input('post.platform');
        $data['password'] = $password = input('post.password');
        $data['sort'] = $sort = input('post.sort');
        $data['uid'] = $uid = input('post.uid');
//        $data['platform_name'] = input('post.platform_name');
//        $data['type'] = input('post.type');
        $data['token'] = input('post.token');
        $rule = [
            'account' => 'require',
            'uid' => 'require|number',
            'token' => 'require',
            'platform' => 'require',
            'password' => 'require',
            'sort' => 'require',
//            'platform_name' => 'require',
//            'type' => 'require',
        ];

        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($data['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        $status = 1;
        $log = '';
/*
        $result = exec("/usr/bin/python /data/wwwroot/api.chuanchuan.tv/public/bindingAccount.py $platform $account $password $sort");

        // 查找是否添加成功
        $model = model('Account');
        $map['account'] = $account;
        $map['uid'] = $uid;
        $map['platform'] = $platform;
        $num = 1;
        while ($num <=30){
            $info = $model->where($map)->find();
            if(!empty($info)){
                return api_return('操作成功！',array());
            }
            $num++;
            sleep(1);
        }*/
        unset($data['token']);
        $model = model('Account');
        $map['account'] = $account;
        $map['uid'] = $uid;
        $map['platform'] = $platform;
        $map['status'] = 1;
        $find = $model->where($map)->find();
        if($find){
            return api_error('3006','您已添加账号，操作失败！');
        }else{
            $platform_name = Db::name('platform')->field('name')->where("id = $platform")->find();
            $data['platform_name'] = $platform_name['name'];
            $data['type'] = 2;
            $data['status'] = 1;
            $result = $model->save($data);
            if($result){
                return api_return('添加账号成功！',array());
            }
        }

        return api_error('3005','操作失败！');
    }

    // 账号修改，只允许修改分类
    public function editAccount(){
        $data['account_id'] = $platform = input('post.account_id');
        $data['sort'] = input('post.sort');
        $data['uid'] = input('post.uid');
        $data['token'] = input('post.token');
        $rule = [
            'account_id' => 'require',
            'uid' => 'require|number',
            'token' => 'require',
            'sort' => 'require',
        ];

        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 进行用户校验
        $checkToken = $this->checkAuthToken($data['token']);
        if(!$checkToken){
            return api_error('9999','请重新登陆！');
        }
        $map['uid'] = $data['uid'];
        $map['id'] = $data['account_id'];
        $saveData['sort'] = $data['sort'];
        $result = Db::name('account')->where($map)->update($saveData);
        if($result){
            return api_return('操作成功！',array());
        }else{
            return api_error('3004','修改失败！');
        }
    }

    // 导入excel分类
    public function import()
    {
        $filename = '/Applications/MAMP/htdocs/chuanchuanapi/public/uploads/omsort.xlsx';
        $reader = \PHPExcel_IOFactory::createReader('Excel2007'); //设置以Excel2007格式
        $PHPExcel = $reader->load($filename); // 载入excel文件
        $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $highestColumm = $sheet->getHighestColumn(); // 取得总列数

        /** 循环读取每个单元格的数据 */
        /** 循环读取每个单元格的数据 */
        $data = array();
        for ($row = 1; $row <= $highestRow; $row++){//行数是以第1行开始

            if($column = 'A'){
                $data['id'] = $sheet->getCell($column.$row)->getValue();
            }

            if($column = 'B'){
                $data['parent'] = $sheet->getCell($column.$row)->getValue();
            }
            if($column = 'C'){
                $data['cat'] = $sheet->getCell($column.$row)->getValue();
            }
            if($column = 'D'){
                $data['name'] = $sheet->getCell($column.$row)->getValue();
            }
            if($column = 'E'){
                $data['type'] = $sheet->getCell($column.$row)->getValue();
            }
            if($column = 'F'){
                $data['platform'] = $sheet->getCell($column.$row)->getValue();
            }
            $tem[] = $data;
        }
        $insert = Db::name('sort')->insertAll($tem);
    }
}